package com.pond.file.utils;

import com.pond.file.config.TosProperties;
import com.pond.file.domain.UploadTosResult;
import com.volcengine.tos.*;
import com.volcengine.tos.model.object.*;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@Service
public class TosService {

    private final TosProperties tosProperties;

    public TosService(TosProperties tosProperties) {
        this.tosProperties = tosProperties;
    }

    public UploadTosResult uploadToTos(MultipartFile file) throws IOException {
        TOSV2 tos = new TOSV2ClientBuilder().build(
                tosProperties.getRegion(),
                tosProperties.getEndpoint(),
                tosProperties.getAccessKey(),
                tosProperties.getSecretKey());

        // 拼接年月“文件夹”，例如 202505/
        String monthFolder = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMM")) + "/";
        String objectKey = monthFolder + UUID.randomUUID() + "_" + file.getOriginalFilename();

        ByteArrayInputStream stream = new ByteArrayInputStream(file.getBytes());

        try {
            PutObjectInput input = new PutObjectInput()
                    .setBucket(tosProperties.getBucket())
                    .setKey(objectKey)
                    .setContent(stream);
            tos.putObject(input);

            String url = "https://" + tosProperties.getBucket() + "." + tosProperties.getEndpoint() + "/" + objectKey;
            return new UploadTosResult(file.getOriginalFilename(), url);
        } catch (TosClientException | TosServerException e) {
            throw new IOException("上传到火山引擎TOS失败: " + e.getMessage(), e);
        }
    }
}
